package cn.jeeweb.web.modules.sys.controller;

import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mvc.controller.BaseBeanController;
import cn.jeeweb.common.utils.FastJsonUtils;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.sys.entity.*;
import cn.jeeweb.web.modules.sys.service.*;
import cn.xjzn.framework_Core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
//import sun.tools.asm.SwitchData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 *
 */
@RestController
@RequestMapping("/ui/property")
@ViewPrefix("modules/UipackageInfo")
//@RequiresPathPermission("ui:packageinfo")
@Log(title = "ui_property")
public class UiPropertyController extends BaseBeanController<UiProperty> {
	@Autowired
	private IUiPropertyService uiPropertyService;

	@Autowired
	private IDictService dictService;

	@Autowired
	private IDictGroupService dictGroupService;

	@Autowired
	private IUiPackageInfoService uiPackageInfoService;

	@Autowired
	IUiControlruleService uiControlruleService;

	@PostMapping("add")
	@Log(logType = ModuleActionType.INSERT)
//	@RequiresMethodPermissions("add")
	public Response add(UiProperty entity, BindingResult result,
						HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		uiPropertyService.insert(entity);
		return Response.ok("添加成功");
	}

	@PostMapping("{id}/update")
	@Log(logType = ModuleActionType.UPDATE)
//	@RequiresMethodPermissions("update")
	public Response update(UiProperty entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		uiPropertyService.insertOrUpdate(entity);
		return Response.ok("更新成功");
	}

	@PostMapping("{id}/delete")
	@Log(logType = ModuleActionType.DELETE)
//	@RequiresMethodPermissions("delete")
	public Response delete(@PathVariable("id") String id) {
		uiPropertyService.deleteById(id);
		return Response.ok("删除成功");
	}

	/**
	 *
	 * @throws IOException
     */
	@RequestMapping(value = "getList", method = { RequestMethod.GET, RequestMethod.POST })
	@Log(logType = ModuleActionType.SELECT)
//	@RequiresMethodPermissions("list")
	public void ajaxList(String...packageIds) throws IOException {
//		String moduleId = "";
//			UiPackageInfo search = new UiPackageInfo();
//			search.setId(uiProperty.getPackageIds()[0]);
//			UiPackageInfo uiPackageInfo = uiPackageInfoService.getUiPackageInfo(search);
//			if(uiPackageInfo != null && StringUtils.isNotBlank(uiPackageInfo.getModuleId())){
//				moduleId = uiPackageInfo.getModuleId();
//			}
//		//List<UiProperty> uiProperties = uiPropertyService.getList(uiProperty);
		List<UiProperty> uiPropertiesFromDB= uiPropertyService.getUiPropertiesFromDB(packageIds);

		List<Dict> dicts = dictService.selectDictList();
		if (uiPropertiesFromDB.size() > 0) {
			for (UiProperty bean : uiPropertiesFromDB) {
				if (bean.getControlType() == 1 && !StringUtils.isEmpty(bean.getDictCode())) {
					bean.setDictItems(getDictsByGid(bean.getDictCode(), dicts));
				}
				if (bean.getHasRule() == 1 && !StringUtils.isEmpty(bean.getControlRule())) {
					String[] array = bean.getControlRule().split("\\|");
//					UiControlRule param = new UiControlRule();
//					param.setIds(array);
//					bean.setControlRules(uiControlruleService.getList(param));
					bean.setControlRules(uiControlruleService.selectBatchIds(Arrays.asList(array)));
				}
			}
		}

		List<UiProperty> uiPropertysFromEntity = new ArrayList<>();
		for (String t:packageIds) {
			List<UiProperty> lst_= uiPropertyService.getUiPropertiesFromEntity(t);
			uiPropertysFromEntity.addAll(lst_);
		}

		//以 数据表配置 覆盖掉 实体配置
		if (uiPropertysFromEntity.size() > 0) {
			uiPropertiesFromDB.forEach(t -> {
				uiPropertysFromEntity.removeIf(r -> r.getOwnerPropertyName().equals(t.getOwnerPropertyName()) && r.getPropertyName().equals(t.getPropertyName()));
			});
			uiPropertysFromEntity.addAll(uiPropertiesFromDB);
			//集合排序
			uiPropertysFromEntity.sort(Comparator.comparing(UiProperty::getDisplayPosition));
		}
		FastJsonUtils.print(uiPropertysFromEntity);
//		return Response.ok(null,uiProperties);
	}

    /**
     * 获取模块的默认属性配置
     * @param packageId 模块ID
     */
	@RequestMapping(value = "getInitProperty", method = { RequestMethod.GET, RequestMethod.POST })
	@Log(logType = ModuleActionType.SELECT)
	public void getInitProperty(String packageId){
		List<UiProperty> uiProperties = uiPropertyService.getUiPropertiesFromEntity(packageId);
		FastJsonUtils.print(uiProperties);
	}

    /**
     * 获取模块的默认属性配置，并保存数据表中。
     * @param packageId 指定包ID，若为空则自动从packageInfo表里找1条
     * @return
     */
	@RequestMapping(value = "saveProperty", method = { RequestMethod.GET, RequestMethod.POST })
	public Response  saveProperty(String packageId){
		UiPackageInfo uiPackageInfo=uiPackageInfoService.selectById(packageId);
		List<UiProperty> uiProperties = uiPropertyService.getUiPropertiesFromEntity(packageId);
		String moduleId=uiPackageInfo.getModuleId();
//		String[] subPackageNames = null;
//		if(!uiPackageInfo.getSubPackageName().isEmpty())
//			subPackageNames = uiPackageInfo.getSubPackageName().split("\\|");
		String childPackageId = "";
//		if(uiPackageInfos.size() > 0){
//			if(StringUtils.isNotBlank(uiPackageInfos.get(0).getSubPackageName())){
//				subPackageName = uiPackageInfos.get(0).getSubPackageName().split("\\|")[0];
//				UiPackageInfo search = new UiPackageInfo();
//				search.setPropertyName(subPackageName);
//				UiPackageInfo childUiPackageInfo = uiPackageInfoService.getUiPackageInfo(search);
//				childPackageId = childUiPackageInfo.getId();
//			}
//		}
		if(!packageId.isEmpty() && !moduleId.isEmpty()) {
			Map<String, Object> where = new HashMap<>();
			where.put("module_Id", moduleId);
			where.put("package_Id", packageId);
			uiPropertyService.deleteByMap(where);
		}
		if(uiProperties != null && uiProperties.size() > 0){
			for(UiProperty uiProperty : uiProperties){
				if(uiProperty.getIsReference()==1){
					uiProperty.setPackageId(packageId);
					uiPropertyService.insert(uiProperty);
					List<UiProperty> referenceUiProperty = uiProperty.getReferenceUiProperty();
					if(referenceUiProperty!=null && referenceUiProperty.size() > 0){
						for(UiProperty bean : referenceUiProperty){
							bean.setPackageId(packageId);
							uiPropertyService.insert(bean);
						}
					}

				}else{
//					if(StringUtils.isNotBlank(uiProperty.getOwnerPropertyName())){
//						List<UiProperty> childUiProperty = uiProperty.getChildUiProperty();
//						if(childUiProperty.size() > 0){
//							for(UiProperty bean : childUiProperty){
//								bean.setPackageId(childPackageId);
//								uiPropertyService.insert(bean);
//							}
//						}
//					}else{
//						uiProperty.setPackageId(packageId);
//						uiPropertyService.insert(uiProperty);
//					}
					uiProperty.setPackageId(packageId);
					uiPropertyService.insert(uiProperty);
				}
			}
		}
		return Response.ok("保存成功");
	}


    private List<Dict> getDictsByGid(String gid, List<Dict> dicts){
		List<Dict> results = new ArrayList<Dict>();
		if(dicts != null && dicts.size() > 0){
			for(Dict dict : dicts){
				if(gid.equals(dict.getGid())){
					results.add(dict);
				}
			}
		}
		return results;
	}

	public List<Dict> getDictsByCode(String code,List<Dict> dicts){
		DictGroup search = new DictGroup();
		search.setCode(code);
		DictGroup dictGroup = dictGroupService.getDictGroupByCode(search);
		String gid = "";
		if(!StringUtils.isEmpty(dictGroup.getId())){
			gid = dictGroup.getId();
		}
		List<Dict> results = new ArrayList<Dict>();
		if(dicts != null && dicts.size() > 0){
			for(Dict dict : dicts){
				if(gid.equals(dict.getGid())){
					results.add(dict);
				}
			}
		}
		return results;
	}

}